package wang.naifei.core.spring.mvc.rest;/*
 * <h3>Title:wheel-parent系统</h3>
 * <p>Copyright (c) 2022, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * <dt>Description:BaseMulitFile</dt>
 * <dd>实现spring org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.StandardMultipartFile的作用</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2022/5/30 17:02</i>
 * @since jdk1.7+
 */
public class SimpleMultipartFile implements MultipartFile {

    private final String name;
    private final String contentType;
    private final InputStream content;
    private final long size;

    public SimpleMultipartFile(String name, String contentType, InputStream content, long size) {
        this.name = name;
        this.contentType = contentType;
        this.content = content;
        this.size = size;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return name;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return size;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return FileCopyUtils.copyToByteArray(content);
    }

    @Override
    public InputStream getInputStream() {
        return content;
    }

    @Override
    public SimpleMultipartFileResource getResource() {
        return new SimpleMultipartFileResource(this);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        if (dest.isAbsolute() && !dest.exists() && dest.canWrite()) {
            FileCopyUtils.copy(content, Files.newOutputStream(dest.toPath()));
        }
    }

    @Override
    public void transferTo(Path dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(content, Files.newOutputStream(dest));
    }
}
